import { Context, Next } from 'koa';
import { logger, httpLogger } from '@/utils/logger';
import { getClientIP } from '@/utils';

/**
 * 请求日志中间件
 */
export const requestLogger = async (ctx: Context, next: Next): Promise<void> => {
  // 简化的日志中间件，跳过 pino-http 集成
  const start = Date.now();
  
  await next();
  
  const responseTime = Date.now() - start;
  logger.info({
    method: ctx.method,
    url: ctx.url,
    status: ctx.status,
    responseTime,
  }, `${ctx.method} ${ctx.url} ${ctx.status} - ${responseTime}ms`);
};

/**
 * 自定义请求日志中间件
 */
export const customRequestLogger = async (ctx: Context, next: Next): Promise<void> => {
  const start = Date.now();
  const clientIP = getClientIP(ctx.request);

  // 记录请求开始
  httpLogger.info({
    request: {
      method: ctx.method,
      url: ctx.url,
      headers: {
        'user-agent': ctx.headers['user-agent'],
        'content-type': ctx.headers['content-type'],
        referer: ctx.headers.referer,
      },
      query: ctx.query,
      clientIP,
    },
  }, '请求开始');

  try {
    await next();
  } finally {
    const responseTime = Date.now() - start;

    // 记录请求结束
    const logLevel = ctx.status >= 400 ? 'warn' : 'info';
    httpLogger[logLevel]({
      request: {
        method: ctx.method,
        url: ctx.url,
        clientIP,
      },
      response: {
        status: ctx.status,
        length: ctx.length,
        responseTime,
      },
    }, `请求完成 ${ctx.method} ${ctx.url} ${ctx.status} - ${responseTime}ms`);
  }
};

export default requestLogger;